//
//  CardManageViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/18.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "CardManageViewController.h"
#import "FillViewController.h"
#import "CardManageModel.h"

@interface CardManageViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UITableView *cardTableView;
@property(nonatomic,strong)NSMutableArray *bankArray;
@property (nonatomic, assign) int idx;

@property(nonatomic,strong) UIButton *noDataBt;
@property(nonatomic,strong)UIButton *tipBt;

@property (nonatomic, assign) int n;
@end

@implementation CardManageViewController

- (void)getHttpData
{
    _n++;
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];

    _noDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;

    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1], @"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] };
    [AppGlobalClass PostDataWithNSstring:BIND_CARD_LIST_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            if(_idx == 0)
            {
                [_bankArray removeAllObjects];
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray objectAtIndex:0];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                self.noDataBt.hidden = TRUE;

                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    CardManageModel *cardManageModel = [[CardManageModel alloc]initWithDictionary:[listArray objectAtIndex:i]];;
                    [_bankArray addObject:cardManageModel];
                }
                
                _idx++;
             

                [_cardTableView reloadData];
                
                if(listArray.count < 10)
                {
                    [_cardTableView.footer noticeNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        _cardTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }

                }
            }
            else
            {
                if (self.bankArray.count==0) {
                    self.noDataBt.hidden = FALSE;
                    
                }
                
                [self.cardTableView.footer noticeNoMoreData];
            }
        }
        [_cardTableView.header endRefreshing];
        [_cardTableView.footer setState:MJRefreshStateIdle];
        [_cardTableView.footer endRefreshing];
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];

    } failure:^(NSError *error){
        [_cardTableView.header endRefreshing];
        [_cardTableView.footer setState:MJRefreshStateIdle];
        [_cardTableView.footer endRefreshing];
        self.noDataBt.hidden = FALSE;
        self.tipBt.hidden = TRUE;
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror){
        [_cardTableView.header endRefreshing];
        [_cardTableView.footer setState:MJRefreshStateIdle];
        [_cardTableView.footer endRefreshing];
        self.tipBt.hidden = FALSE;
        self.noDataBt.hidden = TRUE;

        [self.bankArray removeAllObjects];
        [self.cardTableView reloadData];
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];
}
//没网提示
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}
#pragma mark-再次请求
- (void)buttonAgainTapped:(id)sender
{
    [_cardTableView.header beginRefreshing];
}
#pragma mark alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AppGlobalClass exitLogin];
    
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    
    NSArray *listArray = self.navigationController.viewControllers;
    
    id tabBar = [listArray objectAtIndex:1];
    if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarCon = tabBar;
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
    }
    else
    {
        UITabBarController *tabBarCon = [listArray objectAtIndex:2];
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:TRUE];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[self refreshTheProjectTableView];
    [_cardTableView.header beginRefreshing];
}

-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    
    [self createUI];
    if (!_bankArray) {
        _bankArray = [NSMutableArray array];
    }
}
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"银行卡管理"];
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    
    [self.view addSubview:topView];
    
    if (!_cardTableView) {
        _cardTableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, topView.frame.origin.y+topView.frame.size.height+20.0f, SCREEN_WIDTH, SCREEN_HEIGHT-topView.frame.origin.y-topView.frame.size.height - 10.0f)];
        _cardTableView.delegate = self;
        _cardTableView.dataSource = self;
        _cardTableView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
        [_cardTableView addSubview:self.noDataBt];
        [_cardTableView addSubview:self.tipBt];
         __weak __typeof(self) weakSelf = self;
        
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _cardTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheProjectTableView];
        }];
        
        // 马上进入刷新状态
      //  [_cardTableView.header beginRefreshing];
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
        footerView.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
        
        
        UIButton *addBt = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 10.0f, SCREEN_WIDTH, 44.0f)];
        [addBt setBackgroundColor:[UIColor whiteColor]];
        [addBt setTitle:@"添加银行卡" forState:UIControlStateNormal];
        [addBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [addBt addTarget:self action:@selector(buttonAddTapped:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:addBt];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2-80.0f, 10.0f, 22.0f, 22.0f)];
        img.image = [UIImage imageNamed:@"jia"];
        [addBt addSubview:img];
        _cardTableView.tableFooterView = footerView;
        
        [self.view addSubview:_cardTableView];
    }
}


#pragma mark- tableViewDatasource &delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        UILabel *bankNameLab = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, 20.0f, SCREEN_WIDTH-70.0f, 20.0f)];
        bankNameLab.font = [UIFont systemFontOfSize:20.0f];
        bankNameLab.textAlignment = NSTextAlignmentLeft;
        [bankNameLab setTag:100];
        [cell addSubview:bankNameLab];
        
        UILabel *cardNumLab = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, bankNameLab.frame.origin.y+bankNameLab.frame.size.height+20.0f, SCREEN_WIDTH-70.0f, 20.0f)];
        cardNumLab.textAlignment = NSTextAlignmentLeft;
        cardNumLab.textColor = [UIColor grayColor];
        cardNumLab.font = [UIFont systemFontOfSize:17.0f];
        [cardNumLab setTag:101];
        [cell addSubview:cardNumLab];
    }
    
    CardManageModel *cardManageModel = [_bankArray objectAtIndex:indexPath.row];
    
    UILabel *modelBankNameLab = (UILabel *)[cell viewWithTag:100];
    modelBankNameLab.text = cardManageModel.bankName;
    
    UILabel *modelCardNumLab = (UILabel *)[cell viewWithTag:101];
    modelCardNumLab.text = [self secureThePhoneNum:cardManageModel.accountNo];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_bankArray count];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle ==  UITableViewCellEditingStyleDelete)
    {
        CardManageModel *cardManageModel = [_bankArray objectAtIndex:indexPath.row];
        NSDictionary *dict = @{ @"token" : [[NSUserDefaults standardUserDefaults]objectForKey:@"token"], @"userCardId":cardManageModel.userCardId };
        
        [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
        [AppGlobalClass PostDataWithNSstring:DELETE_CARD_URL withDictionary:dict success:^(NSDictionary *dictionary){
            if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
            {
                [_bankArray removeObjectAtIndex:indexPath.row];
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                 [[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithInt:0] forKey:@"cardVStatus"];
            }
            else
            {
                ALERT_VIEW([dictionary objectForKey:@"message"]);
            }
            [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        } failure:^(NSError *error){
            [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        } networkerror:^(NSString *networkerror){
            [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        }];
    }
}

- (void)buttonAddTapped:(id)sender
{
    FillViewController *fillViewCon = [[FillViewController alloc]init];
    [self.navigationController pushViewController:fillViewCon animated:TRUE];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0f;
}

//刷新表
-(void)refreshTheProjectTableView
{
    _idx = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{

    [self getHttpData];
}
//给银行卡加*号
-(NSString *)secureThePhoneNum:(NSString *)phoneNum
{
    if (phoneNum.length==19) {
        return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, phoneNum.length-7) withString:@"************"];
    }
    else
    {
        return [phoneNum stringByReplacingCharactersInRange:NSMakeRange(3, phoneNum.length-7) withString:@"*********"];
    }
    
}

#pragma mark-取消按钮方法
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
